<template>
  <div class="wrap">
    <div>
      <van-button size="small" class="leftfloat" type="default" @click="closeMap">关闭</van-button>
      <van-button size="small" class="rightfloat" type="info" @click="sure">确认</van-button>
    </div>

    <div>

    </div>

    <div id="container"></div>
    <input id="pickerInput" v-model="addressKeyWord" clearable label="详细地址" placeholder="请输入关键字" />
  </div>

</template>
<script>
import Vue from 'vue'
import wx from 'weixin-js-sdk'
import { Search, List, Cell, PullRefresh, Toast, Tabbar, TabbarItem, Popup, DatetimePicker, ActionSheet, Tab, Tabs, Collapse, CollapseItem, CheckboxGroup, Checkbox, Uploader, Overlay, Loading } from 'vant'
Vue.use(Search).use(List).use(Cell).use(PullRefresh).use(Toast).use(Tabbar).use(TabbarItem).use(Popup).use(DatetimePicker).use(ActionSheet).use(Tab).use(Tabs).use(Collapse).use(CollapseItem).use(CheckboxGroup).use(Checkbox).use(Uploader).use(Overlay).use(Loading)
export default {
  data () {
    return {
      lnglat: [116.397428, 39.90923],
      addressKeyWord: '',
      locationName: '北京市天安门',
      sval: this.$route.params.sval,
      svalmap: this.$route.params.svalmap,
      curName: this.$route.params.curName,
      logintype: this.$store.state.logintype
    }
  },
  mounted () {
    let _this = this
    this.handleInitMap()
    // //console.log('sval',JSON.stringify(this.sval))
    //console.log('svalmap', JSON.stringify(this.svalmap))
    //console.log('name', this.$route.params.curName)
    let ori = this.$route.params.svalmap.value
    if (ori) {
      let oris = ori.split('&')
      this.addressKeyWord = oris[0]
      this.lnglat = oris[1].split(',')

      this.map.clearMap()
      this.handleAddMarker()
      this.map.setCenter(this.lnglat)
    }
    let curName = this.$route.params.curName
    if (!curName) {
      // 地址为空，定位
      if (this.logintype === 'wechat' || this.logintype === 'wxwork') {
        wx.getLocation({
          success: function (res) {
            alert('wx ' + JSON.stringify(res))
          },
          fail: function (res) {
            alert(' wx定位失败 ' + JSON.stringify(res))
          }
        })
      } else {
        AMap.plugin('AMap.Geolocation', function () {
          var geolocation = new AMap.Geolocation({
            enableHighAccuracy: true,
            timeout: 10000,
            zoomEnable: false,
            dragEnable: false,
            showButton: false,
            buttonOffset: new AMap.Pixel(10, 20),
            zoomToAccuracy: true
          })
          geolocation.getCurrentPosition(function (status, result) {
            //console.log(result)
            // alert(JSON.stringify(result));
            if (status === 'complete') {
              curName = result.formattedAddress + '&' + result.position
              _this.getLocation(curName)
            } else {
              alert(' 定位失败 ' + status + JSON.stringify(result))
            }
          })
        })
      }
    } else {
      _this.getLocation(curName)
    }
    // alert('name' + this.$route.params.curName)
  },
  methods: {
    getLocation (curName) {
      // alert('in getLocation')
      // 这里用了我自己的key  shilei
      const key = 'f441ca3dcee01f0d5a18f2624ef5c322'
      this.axios({
        method: 'get',
        url:`https://restapi.amap.com/v3/geocode/geo?key=${key}&address=${curName}`
      }).then((res) => {
        // alert(JSON.stringify(res))
        if (res.data.info === 'OK') {
          const location = res.data.geocodes[0].location.split(',')
          this.lnglat[0] = location[0]
          this.lnglat[1] = location[1]
          this.addressKeyWord = curName

          this.map.clearMap()
          this.handleAddMarker()
          this.map.setCenter(this.lnglat)
        } else {
          alert('地址解析失败！')
        }
      })
    },
    closeMap () {
      //console.log(this.flag + '关了')
      this.$router.go(-1)
    },
    sure () {
      // 回写
      // this.$toast(item.id + '-->' + item.title)
      this.flag = '回写'
      this.$router.go(-1)
    },
    handleInitMap () {
      this.map = new AMap.Map('container', {
        resizeEnable: true, // 是否监控地图容器尺寸变化
        zoom: 14, // 初始化地图层级
        center: this.lnglat // 初始化地图中心点
        // resizeEnable: true
      })
      this.handleAddMarker()
      this.map.on('click', (ev) => {
        // 触发事件的地理坐标，AMap.LngLat 类型
        var lnglat = ev.lnglat
        //console.log(ev, lnglat)
        this.lnglat = [lnglat.lng, lnglat.lat]
        this.map.clearMap()
        this.handleAddMarker()
        this.map.setCenter(this.lnglat)
        // 将经纬度坐标转化为详细地址
        AMap.plugin('AMap.Geocoder', () => {
          var geocoder = new AMap.Geocoder({
            extensions: 'all'
            // city 指定进行编码查询的城市，支持传入城市名、adcode 和 citycode
          })

          var lnglat1 = [lnglat.lng, lnglat.lat]

          geocoder.getAddress(lnglat1, (status, result) => {
            if (status === 'complete' && result.info === 'OK') {
              // result为对应的地理位置详细信息
              //console.log(result, '详细地址')
              this.addressKeyWord = result.regeocode.formattedAddress
              this.locationName = result.regeocode.pois[0].name
            }
          })
        })
      })
      // 加载BasicControl，loadUI的路径参数为模块名中 'ui/' 之后的部分
      AMapUI.loadUI(['control/BasicControl'], (BasicControl) => {
        // 缩放控件
        this.map.addControl(new BasicControl.Zoom({
          position: 'rb', // left top，左上角
          showZoomNum: false // 显示zoom值
        }))
      })
      // 加载PoiPicker，loadUI的路径参数为模块名中 'ui/' 之后的部分
      AMapUI.loadUI(['misc/PoiPicker'], (PoiPicker) => {
        var poiPicker = new PoiPicker({
          input: 'pickerInput' // 输入框id
        })
        // 监听poi选中信息
        poiPicker.on('poiPicked', (poiResult) => {
          // 用户选中的poi点信息
          //console.log(poiResult, 'poiResult')
          let lnglat = poiResult.item.location
          this.addressKeyWord = poiResult.item.name
          this.lnglat = [lnglat.lng, lnglat.lat]
          this.map.clearMap()
          this.handleAddMarker()
          this.map.setCenter(this.lnglat)
        })
      })
    },
    handleAddMarker () {
      // 构造点标记
      const marker = new AMap.Marker({
        icon: 'https://webapi.amap.com/theme/v1.3/markers/n/mark_b.png',
        position: this.lnglat
      })
      // 构造矢量圆形
      // const circle = new AMap.Circle({
      //   center: new AMap.LngLat(this.lnglat[0], this.lnglat[1]), // 圆心位置
      //   radius: 1000,  //半径
      //   strokeColor: "#1890ff",  //线颜色
      //   strokeOpacity: 1,  //线透明度
      //   strokeWeight: 3,  //线粗细度
      //   fillColor: "#1890ff",  //填充颜色
      //   fillOpacity: 0.35 //填充透明度
      // })

      // 将以上覆盖物添加到地图上
      // 单独将点标记添加到地图上
      this.map.add(marker)
      // add方法可以传入一个覆盖物数组，将点标记和矢量圆同时添加到地图上
      // this.map.add([marker, circle])
    }
  },
  beforeRouteLeave (to, from, next) {
    if (to.name === 'new' || to.name === 'edit' || to.name === 'qiandaonew') {
      if (this.flag) {
        for (let groupindex in this.sval) {
          for (let itemindex in this.sval[groupindex].groupvalue) {
            let item = this.sval[groupindex].groupvalue[itemindex]
            if (item.sField === this.svalmap.sField) {
              //console.log(item.value + 'map')
              alert('位置:' + this.addressKeyWord)
              item.value = this.addressKeyWord + '&' + this.lnglat
              // this.isPosi = false
            }
          }
        }
      }
    }
    next()
  }
}
</script>
<style lang="scss" scoped>
#container {
  width: 100%;
  height: 500px;
}

#pickerInput {
  background-image: url(https://a.amap.com/jsapi_demos/static/image/search.png);
  background-repeat: no-repeat;
  background-position: right;
  background-size: 16px;
  font-family: inherit;
  display: block;
  width: 100%;
  height: 2.4rem;
  padding: .5rem;
  margin-bottom: -9px;
  border: 1px solid #E1E1E2;
  font-size: .875rem;
  border-radius: 1px;
  box-sizing: border-box;
  margin-bottom: 5px;
}

.leftfloat {
  position: absolute;
  left: 1vw;
  top: 1vh;
  z-index: 99;
}

.rightfloat {
  position: absolute;
  right: 1vw;
  top: 1vh;
  z-index: 99;
}
</style>
